﻿#include "NosepieceYN.h"
#include <QDebug>
NosepieceYN::NosepieceYN(QObject *parent)
    : QObject(parent),
    m_lens(-1),
    m_state(0),
    m_serialPort(nullptr)
{
    m_serialPort = new QSerialPort(this);
    m_serialPort->setBaudRate(QSerialPort::Baud9600, QSerialPort::AllDirections);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setStopBits(QSerialPort::OneStop);
    connect(m_serialPort, SIGNAL(readyRead()), this, SLOT(on_readyRead()));

    m_timer = new QTimer(this);
    m_timer->setSingleShot(true);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(on_timer()));
}

NosepieceYN::~NosepieceYN()
{
    //delete m_serialPort;
    //delete m_timer;
}

void NosepieceYN::on_readyRead()
{
//    qDebug() << "on_readyRead";
    QByteArray arr = m_serialPort->readAll();
    QByteArray::iterator i;
    for (i = arr.begin(); i != arr.end(); ++i)
    {
        //qDebug() << int(*i);
        state(*i);
    }
}

void NosepieceYN::on_timer()
{
    m_state = 0;
    emit timeout();
}

void NosepieceYN::state(unsigned char s)
{
    qDebug() << "m_state = " << m_state;
    qDebug() << "s = " << s;
    switch (m_state)
    {
    case 0: // 等待收到 0xDF
        if(s == 0xDF)
        {
            m_state = 1;
            return ;
        }
        else // 收到其他的都有问题
        {
            emit error();
        }
        break;
    case 1:
        if( s == 0x0A + m_newLens )
        {
            int old = m_lens;
            m_lens = m_newLens;
            m_state = 0;
            m_timer->stop();
            qDebug() << old;
            qDebug() << m_lens;
            emit lensChanged(old, m_lens);
            return;
        }
        else
        {
            m_state = 0;
            emit error();
        }
    default:
        m_state = 0;
        break;
    }
}

bool NosepieceYN::open(QString port)
{
    if(m_serialPort->isOpen())
    {
        m_serialPort->close();
    }
    m_serialPort->setPortName(port);
    if(m_serialPort->open(QIODevice::ReadWrite))                    //如能打开串口，则设置串口
    {
        m_serialPort->clearError();
        m_serialPort->clear();
        setLens(0);
        return true;
    }
    return false;
}

void NosepieceYN::setLens(int n)
{
    m_newLens = n;
    if(n >= 0 && n <= 3)
    {
        m_serialPort->putChar(0x0A + n);
    }
    m_timer->start(4000);

}

void NosepieceYN::setLens(int oldLens,int newLens)
{
    Q_UNUSED(oldLens);
    setLens(newLens);
}

void NosepieceYN::close()
{
    m_serialPort->close();
}

void NosepieceYN::forward()
{
    if(m_lens < 3)
    {
        setLens(m_lens + 1);
    }
}

void NosepieceYN::reverse()
{
    if(m_lens > 0)
    {
        setLens(m_lens - 1);
    }
}
